const Router = require('koa-router');
const teafeaCtl= require('../../controllers/teamfeatures.js');
const matchCtl= require('../../controllers/matches.js');
const teamCtl= require('../../controllers/teams.js');
const playerCtl= require('../../controllers/players.js');
const plyfeaCtl= require('../../controllers/playerfeatures.js')
const router = new Router();

/**
 * @swagger
 * tags:
 *   - name: competition
 *     description: Everything about competition
 */

router
/**
 * @swagger
 * paths:
 *   /competitions:
 *     get:
 *       tags:
 *         - competition
 *       summary: Return a list of competitions
 *       description: ''
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 *           schema:
 *             type: array
 *             items:
 *               $ref: '#/definitions/Competition'
 */
    .get('/', async (ctx, next)=>{ ctx.body = await teafeaCtl.list(); })

/**
 * @swagger
 * paths:
 *   /competitions:
 *     post:
 *       tags:
 *         - competition
 *       summary: Create a competition
 *       description: ''
 *       parameters:
 *         - in: body
 *           name: "body"
 *           description: ""
 *           required: true
 *           schema:
 *             $ref: "#/definitions/Competition"
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .post('/', async (ctx, next)=>{
        const {id} = ctx.params;
        const data = ctx.request.body;
        let  r = await teafeaCtl.create(data);
        ctx.body = r;
    })
/**
 * @swagger
 * paths:
 *   /competitions/{cid}:
 *     get:
 *       tags:
 *         - competition
 *       summary: Return a competition
 *       description: ''
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 *           schema:
 *             $ref: '#/definitions/Competition'
 */
    .get('/:id', async (ctx, next)=>{
        // Retrieves informations about a given competition
        const {id} = ctx.params;
        const r = await teafeaCtl.retrieve(id);
        ctx.assert(r !== null, 404, 'Detail not found!');

        ctx.body = r;
    })

/**
 * @swagger
 * paths:
 *   /competitions/{cid}:
 *     put:
 *       tags:
 *         - competition
 *       summary: Update or create a competition
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *         - in: body
 *           name: body
 *           description: ""
 *           required: true
 *           schema:
 *             $ref: "#/definitions/Competition"
 *
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .put('/:id', async (ctx, next)=>{
        const id = ctx.params.id;
        const data = ctx.request.body;
        const r = await teafeaCtl.upsert(id, data);
        
        ctx.body = r;
    })

/**
 * @swagger
 * paths:
 *   /competitions/{cid}:
 *     delete:
 *       tags:
 *         - competition
 *       summary: Delete a competition
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *
 *       produces:
 *         - application/json
 *       responses:
 *         204:
 *           description: No content
 */
    .delete('/:id', async (ctx, next)=>{
        teafeaCtl.removeById(ctx.params.id);
        ctx.status = 204;
    })
/**
 * @swagger
 * paths:
 *   /competitions/{cid}/seasons:
 *     get:
 *       tags:
 *         - competition
 *       summary: Return the list of seasons of the given competition
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .get('/:id/seasons', async (ctx, next)=>{
        const {id} = ctx.params;
        ctx.body = "TODO find the list of seasons of competition" + id;
        ctx.throw(500);
    })

    .get('/:seasonid/:teamid', async (ctx, next)=>{
        const {seasonid, teamid} = ctx.params;
        const team = await teafeaCtl.find({teamId: teamid});
        //console.log(team)
        let result = {}, yellowCard = 0, redCard = 0, attackScore = 0, defenseScore = 0, organizeScore = 0, skillScore = 0, setScore = 0, passScore = 0, i = 0;
        for (let a of team){
            for (let key of Object.keys(a)){
                let b = a[key]
                for (let key1 of Object.keys(b)){
                    let teamidt = b[key1]
                    if (key1 == seasonid){
                        attackScore = attackScore + teamidt.attackScore;
                        defenseScore = defenseScore + teamidt.defenseScore;
                        organizeScore = organizeScore + teamidt.organizeScore;
                        skillScore = skillScore + teamidt.skillScore;
                        setScore = setScore + teamidt.setScore;
                        passScore = passScore + teamidt.passScore;
                        yellowCard = yellowCard + teamidt.yellowCard;
                        redCard = redCard + teamidt.redCard;
                        i++
                    }
                    else {
                        continue;
                    }
                }
            }
        }
        const r = await teamCtl.find();
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        let Result = []
        for (let a of r){
            //let win = 0, draw = 0, lose = 0, goal = 0, conceded = 0;
            teamId = a.teamId
            //console.log(teamId)
            const match = await matchCtl.find({$or:[{home_team_id: teamId},{away_team_id: teamId}], season: seasonid});
            //console.log(matches)
            if (match.length != 0){
                let matches = match;
                //matches = matches.sort(compare('round'))
                //console.log(matches)
                let obj = {}, win = 0, draw = 0, lose = 0, goal = 0, conceded = 0;
                obj.rank = 0;
                for (let b of matches){
                    if (b.home_team_id == teamId){
                        goal = goal + b.home_score;
                        conceded = conceded + b.away_score;
                        if (b.home_score > b.away_score){
                            win = win + 1
                        }
                        else if (b.home_score == b.away_score){
                            draw = draw + 1
                        }
                        else if (b.home_score < b.away_score){
                            lose = lose + 1
                        }
                    }
                    else if (b.away_team_id == teamId){
                        goal = goal + b.away_score;
                        conceded = conceded + b.home_score;
                        if (b.home_score > b.away_score){
                            lose = lose + 1
                        }
                        else if (b.home_score == b.away_score){
                            draw = draw + 1
                        }
                        else if (b.home_score < b.away_score){
                            win = win + 1
                        }
                    }
                }
                obj.teamId = teamId;
                //obj.games = win + draw + lose;
                obj.win = win;
                obj.draw = draw;
                obj.lose = lose;
                obj.goal = goal;
                obj.conceded = conceded;
                //obj.difference = goal - conceded;
                obj.points = win * 3 + draw;
                //obj.recentResult = recentresult;
                Result.push(obj)
            }
            else {
                continue;
            }
        }
        Result = Result.sort(compare('points'));
        let i1 = 0;
        result.teamId = parseInt(teamid);
        for (let a of Result){
            i1++;
            if (a.teamId == teamid) {
                result.rank = i1;
                result.win = a.win;
                result.draw = a.draw;
                result.lose = a.lose;
                result.goal = a.goal;
                result.conceded = a.conceded;
            }
            else {
                continue;
            }
        }
        result.attackScore = parseFloat((attackScore / i).toFixed(2));
        result.defenseScore = parseFloat((defenseScore / i).toFixed(2));
        result.organizeScore = parseFloat((organizeScore / i).toFixed(2));
        result.skillScore = parseFloat((skillScore / i).toFixed(2));
        result.setScore = parseFloat((setScore / i).toFixed(2));
        result.passScore = parseFloat((passScore / i).toFixed(2));
        result.yellowCard = yellowCard;
        result.redCard = redCard;
        ctx.body = result;
    })

    .get('/matchlist/:competitionid/:seasonid/:teamid', async (ctx, next)=>{
        const {competitionid, seasonid, teamid} = ctx.params;
        const matches = await matchCtl.find({season: seasonid, competitionId: competitionid, $or:[{home_team_id:teamid},{away_team_id:teamid}]});
        let result = []
        for (let a of matches){
            let obj = {};
            obj.round = a.round;
            obj.matchId = a.matchId;
            const home = await teamCtl.find({teamId: a.home_team_id})
            for (let b of home){
                for (let key of Object.keys(b['name'])){
                    if (key == seasonid){
                        let team = b['name'][key];
                        obj.homeTeamId = a.home_team_id;
                        obj.homeTeam = team.offcialName.slice(0,4);
                        obj.homeTeamImg = team.teamImg;
                    }
                }
            }
            const away = await teamCtl.find({teamId: a.away_team_id})
            for (let c of away){
                for (let key of Object.keys(c['name'])){
                    if (key == seasonid){
                        let team = c['name'][key];
                        obj.awayTeamId = a.away_team_id;
                        obj.awayTeam = team.offcialName.slice(0,4);
                        obj.awayTeamImg = team.teamImg;
                    }
                }
            }
            obj.score = a.home_score + "-" + a.away_score;
            obj.matchTime = a.match_time.slice(0,-3);
            const h = await teamCtl.find({teamId: a.home_team_id})
            for (let b of h){
                obj.stadium = b.stadiumName + ',' + b.city;
            }
            result.push(obj)
        }
        ctx.body = result;
    })

    .get('/players/:seasonid/:teamid', async (ctx, next)=>{
        const {seasonid, teamid} = ctx.params;
        const players = await playerCtl.list();
        //console.log(players);
        let result = [], forward = [], midfielder = [], defender = [], goalkeeper = [];
        for (let a of players) {
            for (let key of Object.keys(a.team)) {
                if (key == seasonid) {
                    let team = a.team[key];
                    if (team.teamId == teamid) {
                        let obj = {};
                        switch (a.role) {
                            case 'GK':
                                obj.role = '门将';
                                break;
                            case 'DF':
                                obj.role = '后卫';
                                break;
                            case 'MF':
                                obj.role = '中场';
                                break;
                            case 'ST':
                                obj.role = '前锋';
                                break;
                            default:
                                break;
                        }
                        obj.playerId = a.playerId;
                        /*obj.teamId = team.teamId;
                        obj.season = key;*/
                        obj.number = team.teamNum;
                        obj.playerLogo = a.playerImg;
                        obj.name = a.playerName;
                        obj.nationality = a.country;
                        obj.countryLogo = a.countryImg;
                        let appearance = 0, lineUp = 0, minutes = 0, goals = 0, assists = 0, yellowCard = 0, redCard = 0;
                        const plyfea = await plyfeaCtl.find({playerId: a.playerId});
                        for (let b of plyfea) {
                            for (let key1 of Object.keys(b)){
                                if (parseFloat(key1).toString() != "NaN"){
                                    for (let key2 of Object.keys(b[key1])){
                                        if (key2 == seasonid) {
                                            let playerfea = b[key1][key2];
                                            appearance = appearance + playerfea.appearance;
                                            lineUp = lineUp + playerfea.lineUp;
                                            minutes = minutes + playerfea.minutes;
                                            if (a.role == 'GK') {
                                                goals = goals + playerfea.totalSave;
                                                assists = assists + playerfea.totalSmother;
                                            }
                                            else {
                                                goals = goals + playerfea.totalGoal;
                                                assists = assists + playerfea.totalAssist;
                                            }
                                            yellowCard = yellowCard + playerfea.yellowCard;
                                            redCard = redCard + playerfea.redCard;
                                        }
                                        else {
                                            continue;
                                        }
                                    }
                                }
                                else {
                                    continue;
                                }
                            }
                        }
                        obj.appearance = appearance + '(' + lineUp + ')';
                        obj.minutes = minutes;
                        obj.goals = goals;
                        obj.assists = assists;
                        obj.cards = yellowCard + '/' + redCard;
                        result.push(obj)
                        /*switch (a.role) {
                            case 'GK':
                                goalkeeper.push(obj);
                                break;
                            case 'DF':
                                defender.push(obj);
                                break;
                            case 'MF':
                                midfielder.push(obj);
                                break;
                            case 'ST':
                                forward.push(obj);
                                break;
                            default:
                                break;
                        }*/
                    }
                    else {
                        continue;
                    }
                }
                else {
                    continue;
                }
            }
        }
        //result.push(forward);
        //result.push(midfielder);
        //result.push(defender);
        //result.push(goalkeeper);
        ctx.body = result;
    })

    .get('/offense/:competitionid/:seasonid/:teamid', async (ctx, next)=>{
        const {competitionid, seasonid, teamid} = ctx.params;
        const features = await teafeaCtl.list();
        let shot = [], assist = [];
        for (let a of features){
            for (let key of Object.keys(a)){
                if (key == competitionid){
                    for (let key1 of Object.keys(a[key])){
                        if (key1 == seasonid){
                            let teamfea = a[key][key1];
                            let obj = {
                                'rank': 0,
                                'teamId': a.teamId,
                                'name': 0,
                                'total': teamfea.totalShot,
                                'goals': teamfea.totalGoal,
                                'rate': teamfea.totalGoal / teamfea.totalShot || 0,
                                'xG': teamfea.xG
                            }
                            let obj1 = {
                                'rank': 0,
                                'teamId': a.teamId,
                                'name': 0,
                                'total': teamfea.totalAssist,
                                //'average': (playerfea.totalShot / playerfea.minutes || 0) * 90,
                                'xA': teamfea.xA
                            }
                            assist.push(obj1);
                            shot.push(obj);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    continue;
                }
            }
        }
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        shot = shot.sort(compare('total'));
        assist = assist.sort(compare('total'));
        let i1 = 0, i2 = 0;
        for (let a of shot){
            i1++;
            a.rank = i1;
            a.rate = (a['rate'] * 100).toFixed(2) + '%';
            a.xG = parseFloat(a['xG'].toFixed(2));
        }
        for (let b of assist){
            i2++;
            b.rank = i2;
            //b.average = parseFloat(b['average'].toFixed(2));
            b['xA'] = parseFloat(b['xA'].toFixed(2));
        }
        //console.log(assist);
        //console.log(shot);
        let shootData = [], assistData = [], result = {};
        for (let a of shot){
            if (a.teamId == teamid) {
                if (a.rank <= 5){
                    for(let b of shot) {
                        if(b.rank <=8) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            shootData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of shot){
                        if(b.rank == 1) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            shootData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            shootData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        for (let a of assist){
            if (a.teamId == teamid) {
                if (a.rank <= 5){
                    for(let b of assist) {
                        if(b.rank <=8) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            assistData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of assist){
                        if(b.rank == 1) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            assistData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            assistData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        result.shootData = shootData;
        result.assistData = assistData;
        ctx.body = result;
    })

    .get('/organization/:competitionid/:seasonid/:teamid', async (ctx, next)=>{
        const {competitionid, seasonid, teamid} = ctx.params;
        const features = await teafeaCtl.list();
        let pass = [], cross = [];
        for (let a of features){
            for (let key of Object.keys(a)){
                if (key == competitionid){
                    for (let key1 of Object.keys(a[key])){
                        if (key1 == seasonid){
                            let teamfea = a[key][key1];
                            let obj = {
                                'rank': 0,
                                'teamId': a.teamId,
                                'name': 0,
                                'total': teamfea.totalPass,
                                //'goals': teamfea.totalGoal,
                                'rate': teamfea.passAccuracy,
                                'zone': ((teamfea['pass front accuracy'] * 100).toFixed(2) + '%') + '/' + ((teamfea['pass mid accuracy'] * 100).toFixed(2) + '%') + '/' + ((teamfea['pass back accuracy'] * 100).toFixed(2) + '%')
                            }
                            let obj1 = {
                                'rank': 0,
                                'teamId': a.teamId,
                                'name': 0,
                                'total': teamfea.totalCross,
                                //'average': (playerfea.totalShot / playerfea.minutes || 0) * 90,
                                'zone': ((teamfea['crosses left accuracy'] * 100).toFixed(2) + '%') + '/' + ((teamfea['crosses right accuracy'] * 100).toFixed(2) + '%'),
                                'distance': teamfea['cross distance']
                            }
                            cross.push(obj1);
                            pass.push(obj);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    continue;
                }
            }
        }
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        pass = pass.sort(compare('total'));
        cross = cross.sort(compare('total'));
        let i1 = 0, i2 = 0;
        for (let a of pass){
            i1++;
            a.rank = i1;
            a.rate = (a['rate'] * 100).toFixed(2) + '%';
            //a.xG = parseFloat(a['xG'].toFixed(2));
        }
        for (let b of cross){
            i2++;
            b.rank = i2;
            //b.average = parseFloat(b['average'].toFixed(2));
            b.distance = parseFloat(b['distance'].toFixed(2));
        }
        //console.log(assist);
        //console.log(shot);
        let passData = [], crossData = [], result = {};
        for (let a of pass){
            if (a.teamId == teamid) {
                if (a.rank <= 5){
                    for(let b of pass) {
                        if(b.rank <=8) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            passData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of pass){
                        if(b.rank == 1) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            passData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            passData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        for (let a of cross){
            if (a.teamId == teamid) {
                if (a.rank <= 5){
                    for(let b of cross) {
                        if(b.rank <=8) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            crossData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of cross){
                        if(b.rank == 1) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            crossData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            crossData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        result.passData = passData;
        result.crossData = crossData;
        ctx.body = result;
    })

    .get('/battle/:competitionid/:seasonid/:teamid', async (ctx, next)=>{
        const {competitionid, seasonid, teamid} = ctx.params;
        const features = await teafeaCtl.list();
        let battle = [], foul = [];
        for (let a of features){
            for (let key of Object.keys(a)){
                if (key == competitionid){
                    for (let key1 of Object.keys(a[key])){
                        if (key1 == seasonid){
                            let teamfea = a[key][key1];
                            let obj = {
                                'rank': 0,
                                'teamId': a.teamId,
                                'name': 0,
                                'total': teamfea.totalDuel,
                                //'goals': teamfea.totalGoal,
                                'rate': (teamfea.duelSuccess / teamfea.totalDuel) || 0,
                                //'zone': ((teamfea['pass front accuracy'] * 100).toFixed(2) + '%') + '/' + ((teamfea['pass mid accuracy'] * 100).toFixed(2) + '%') + '/' + ((teamfea['pass back accuracy'] * 100).toFixed(2) + '%')
                            }
                            let obj1 = {
                                'rank': 0,
                                'teamId': a.teamId,
                                'name': 0,
                                'total': teamfea['fouls back'] + teamfea['fouls mid'] + teamfea['fouls forward'],
                                'type': teamfea.totalOffensiveFoul + '/' + teamfea.totalDefensiveFoul,
                                //'average': (playerfea.totalShot / playerfea.minutes || 0) * 90,
                                'offside': teamfea.offsides,
                                'cards': teamfea.yellowCard + '/' + teamfea.redCard
                            }
                            foul.push(obj1);
                            battle.push(obj);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    continue;
                }
            }
        }
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        battle = battle.sort(compare('total'));
        foul = foul.sort(compare('total'));
        let i1 = 0, i2 = 0;
        for (let a of battle){
            i1++;
            a.rank = i1;
            a.rate = (a['rate'] * 100).toFixed(2) + '%';
            //a.xG = parseFloat(a['xG'].toFixed(2));
        }
        for (let b of foul){
            i2++;
            b.rank = i2;
            //b.average = parseFloat(b['average'].toFixed(2));
            //b.distance = parseFloat(b['distance'].toFixed(2));
        }
        //console.log(assist);
        //console.log(shot);
        let battleData = [], foulData = [], result = {};
        for (let a of battle){
            if (a.teamId == teamid) {
                if (a.rank <= 5){
                    for(let b of battle) {
                        if(b.rank <=8) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            battleData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of battle){
                        if(b.rank == 1) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            battleData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            battleData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        for (let a of foul){
            if (a.teamId == teamid) {
                if (a.rank <= 5){
                    for(let b of foul) {
                        if(b.rank <=8) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            foulData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of foul){
                        if(b.rank == 1) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            foulData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            foulData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        result.battleData = battleData;
        result.foulData = foulData;
        ctx.body = result;
    })

    .get('/defense/:competitionid/:seasonid/:teamid', async (ctx, next)=>{
        const {competitionid, seasonid, teamid} = ctx.params;
        const features = await teafeaCtl.list();
        let goalkeep = [], defense = [];
        for (let a of features){
            for (let key of Object.keys(a)){
                if (key == competitionid){
                    for (let key1 of Object.keys(a[key])){
                        if (key1 == seasonid){
                            let teamfea = a[key][key1];
                            let obj = {
                                'rank': 0,
                                'teamId': a.teamId,
                                'name': 0,
                                'save': teamfea.totalSave,
                                //'goals': teamfea.totalGoal,
                                'savePenalty': teamfea['keeper penalty faced'],
                                'pounced': teamfea.totalSmother
                                //'zone': ((teamfea['pass front accuracy'] * 100).toFixed(2) + '%') + '/' + ((teamfea['pass mid accuracy'] * 100).toFixed(2) + '%') + '/' + ((teamfea['pass back accuracy'] * 100).toFixed(2) + '%')
                            }
                            let obj1 = {
                                'rank': 0,
                                'teamId': a.teamId,
                                'name': 0,
                                'interception': teamfea.interceptions,
                                'tackle': teamfea.tackles,
                                //'average': (playerfea.totalShot / playerfea.minutes || 0) * 90,
                                'clearance': teamfea.clearances
                            }
                            defense.push(obj1);
                            goalkeep.push(obj);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    continue;
                }
            }
        }
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        goalkeep = goalkeep.sort(compare('save'));
        defense = defense.sort(compare('tackle'));
        let i1 = 0, i2 = 0;
        for (let a of goalkeep){
            i1++;
            a.rank = i1;
            //a.rate = (a['rate'] * 100).toFixed(2) + '%';
            //a.xG = parseFloat(a['xG'].toFixed(2));
        }
        for (let b of defense){
            i2++;
            b.rank = i2;
            //b.average = parseFloat(b['average'].toFixed(2));
            //b.distance = parseFloat(b['distance'].toFixed(2));
        }
        //console.log(assist);
        //console.log(shot);
        let goalkeepData = [], defenseData = [], result = {};
        for (let a of goalkeep){
            if (a.teamId == teamid) {
                if (a.rank <= 5){
                    for(let b of goalkeep) {
                        if(b.rank <=8) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            goalkeepData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of goalkeep){
                        if(b.rank == 1) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            goalkeepData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            goalkeepData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        for (let a of defense){
            if (a.teamId == teamid) {
                if (a.rank <= 5){
                    for(let b of defense) {
                        if(b.rank <=8) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            defenseData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of defense){
                        if(b.rank == 1) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            defenseData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const teams = await teamCtl.find({teamId: b.teamId})
                            for (let c of teams){
                                for (let key of Object.keys(c['name'])){
                                    if (key == seasonid){
                                        let team = c['name'][key];
                                        //obj.awayTeamId = a.away_team_id;
                                        b.name = team.offcialName.slice(0,4);
                                        b.teamImg = team.teamImg;
                                        //obj.awayTeamImg = team.teamImg;
                                    }
                                }
                            }
                            defenseData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        result.goalkeepData = goalkeepData;
        result.defenseData = defenseData;
        ctx.body = result;
    })

module.exports = router;

/**
 * @swagger
 * resourcePath: /api
 * description: All about API
 * definitions:
 *   Competition:
 *     type: "object"
 *     required:
 *       - "name"
 *     properties:
 *       id:
 *         type: "string"
 *       name:
 *         type: "string"
 *       area:
 *         type: "string"
 *       foramt:
 *         type: "string"
 *         enum:
 *           - "Domestic cup"
 *           - "Domestic league"
 *           - "Domestic super cup"
 *           - "International cup"
 *           - "International super cup"
 *       type:
 *         type: "string"
 *         enum:
 *          - club
 *          - inernational
 *       categroy: 
 *         type: "string"
 *         enum:
 *          - defalut
 *          - U12
 *          - U13
 *          - U14
 *          - U15
 *          - U16
 *          - U17
 *          - U18
 *          - U19
 *          - U20
 *          - U21
 *          - U22
 *          - U23
 *       gender: 
 *         type: "string"
 *         enum:
 *           - male
 *           - female
 *       divisionLevel:
 *         type: "number"
 *         enum:
 *           - 0
 *           - 1
 *           - 2
 *           - 3
 *           - 4
 *           - 5
 */